// 导入模型
const User = require('./models/User')
const { RechargeRecord } = require('./models/RechargeRecord')

// 使用腾讯云直播SDK
const tencentcloud = require('tencentcloud-sdk-nodejs')
const LiveClient = tencentcloud.live.v20180801.Client

// 基础配置
const express = require('express')
const http = require('http')
const socketIo = require('socket.io')
const app = express()
const server = http.createServer(app)
const io = socketIo(server)

// 腾讯云直播配置
const liveClient = new LiveClient({
  credential: {
    secretId: process.env.TENCENT_CLOUD_SECRET_ID,
    secretKey: process.env.TENCENT_CLOUD_SECRET_KEY,
  },
  region: 'ap-shanghai',
  profile: {
    httpProfile: {
      endpoint: 'live.tencentcloudapi.com',
    },
  },
})

// 微信支付配置
const WxPay = require('wechat-pay').Payment
const wxPay = new WxPay({
  appId: process.env.WECHAT_APPID,
  mchId: process.env.WECHAT_MCH_ID,
  partnerKey: process.env.WECHAT_PARTNER_KEY,
  notifyUrl: process.env.WECHAT_NOTIFY_URL,
  pfx: require('fs').readFileSync(process.env.WECHAT_CERT_PATH),
})

// 用户认证
const jwt = require('jsonwebtoken')
const authenticate = (req, res, next) => {
  const token = req.headers['authorization']
  if (!token) return res.status(401).json({ message: '未授权' })

  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET)
    next()
  } catch (error) {
    return res.status(401).json({ message: '无效的token' })
  }
}

// 充值接口
app.post('/recharge', authenticate, async (req, res) => {
  try {
    const { amount } = req.body
    const user = req.user

    // 创建微信支付订单
    const order = await wxPay.createOrder({
      body: '直播平台充值',
      out_trade_no: `RECHARGE_${Date.now()}_${user._id}`,
      total_fee: amount * 100, // 微信支付单位为分
      spbill_create_ip: req.ip,
      notify_url: process.env.WECHAT_NOTIFY_URL,
      trade_type: 'JSAPI',
      openid: user.wechatOpenid,
    })

    res.json({
      success: true,
      data: {
        paymentParams: wxPay.getPaymentParams(order),
        orderId: order.out_trade_no,
      },
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 微信支付回调
app.post('/wechat/notify', async (req, res) => {
  try {
    const result = await wxPay.verifyNotify(req)

    // 更新用户余额
    const userId = result.out_trade_no.split('_')[2]
    const amount = result.total_fee / 100

    await User.findByIdAndUpdate(userId, {
      $inc: { balance: amount },
    })

    // 创建充值记录
    await RechargeRecord.create({
      userId,
      amount,
      orderId: result.out_trade_no,
      status: 'success',
      paymentMethod: 'wechat',
      transactionId: result.transaction_id,
    })

    res.send('<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>')
  } catch (error) {
    console.error('支付回调处理失败:', error)

    // 记录支付失败
    const orderId = req.body.out_trade_no
    if (orderId) {
      await RechargeRecord.findOneAndUpdate(
        { orderId },
        {
          status: 'failed',
          error: error.message,
        }
      )
    }

    res.status(500).send('<xml><return_code><![CDATA[FAIL]]></return_code></xml>')
  }
})

// 支付失败重试
app.post('/recharge/retry', authenticate, async (req, res) => {
  try {
    const { orderId } = req.body
    const record = await RechargeRecord.findOne({ orderId })

    if (!record) {
      return res.status(404).json({ message: '订单不存在' })
    }

    if (record.status !== 'failed') {
      return res.status(400).json({ message: '只有失败的订单可以重试' })
    }

    // 创建新的支付订单
    const order = await wxPay.createOrder({
      body: '直播平台充值',
      out_trade_no: `RECHARGE_${Date.now()}_${record.userId}`,
      total_fee: record.amount * 100,
      spbill_create_ip: req.ip,
      notify_url: process.env.WECHAT_NOTIFY_URL,
      trade_type: 'JSAPI',
      openid: req.user.wechatOpenid,
    })

    // 更新原记录状态
    await RechargeRecord.findByIdAndUpdate(record._id, {
      status: 'pending',
      retryCount: (record.retryCount || 0) + 1,
    })

    res.json({
      success: true,
      data: {
        paymentParams: wxPay.getPaymentParams(order),
        orderId: order.out_trade_no,
      },
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 充值记录查询
app.get('/recharge/history', authenticate, async (req, res) => {
  try {
    const { page = 1, limit = 10, startDate, endDate, status } = req.query
    const query = { userId: req.user._id }

    // 添加时间范围过滤
    if (startDate && endDate) {
      query.createdAt = {
        $gte: new Date(startDate),
        $lte: new Date(endDate),
      }
    }

    // 添加状态过滤
    if (status) {
      query.status = status
    }

    const records = await RechargeRecord.find(query)
      .sort({ createdAt: -1 })
      .skip((page - 1) * limit)
      .limit(Number(limit))

    const total = await RechargeRecord.countDocuments(query)

    res.json({
      success: true,
      data: {
        records,
        pagination: {
          page: Number(page),
          limit: Number(limit),
          total,
          totalPages: Math.ceil(total / limit),
        },
      },
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 充值统计
app.get('/recharge/stats', authenticate, async (req, res) => {
  try {
    const { type = 'user', startDate, endDate } = req.query
    const match = {}

    // 时间范围过滤
    if (startDate && endDate) {
      match.createdAt = {
        $gte: new Date(startDate),
        $lte: new Date(endDate),
      }
    }

    // 用户统计
    if (type === 'user') {
      match.userId = req.user._id
    }

    const stats = await RechargeRecord.aggregate([
      { $match: match },
      {
        $group: {
          _id: '$paymentMethod',
          totalAmount: { $sum: '$amount' },
          count: { $sum: 1 },
        },
      },
      {
        $project: {
          _id: 0,
          paymentMethod: '$_id',
          totalAmount: 1,
          count: 1,
        },
      },
    ])

    res.json({
      success: true,
      data: stats,
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 直播管理
app.post('/live/create', authenticate, async (req, res) => {
  try {
    const { title, description } = req.body

    const params = {
      StreamName: `room_${Date.now()}`,
      AppName: 'live',
      DomainName: process.env.TENCENT_LIVE_DOMAIN,
      EndTime: new Date(Date.now() + 3600 * 1000).toISOString(),
    }

    const result = await liveClient.CreateLiveStream(params)

    res.json({
      success: true,
      data: {
        ...result,
        pushUrl: `rtmp://${process.env.TENCENT_LIVE_DOMAIN}/live/${params.StreamName}`,
        playUrl: `https://${process.env.TENCENT_LIVE_DOMAIN}/live/${params.StreamName}.flv`,
      },
    })
  } catch (error) {
    res.status(500).json({ message: error.message })
  }
})

// 礼物配置
const gifts = [
  { id: 1, name: '玫瑰', price: 1 },
  { id: 2, name: '跑车', price: 50 },
  { id: 3, name: '游轮', price: 100 },
  { id: 4, name: '火箭', price: 500 },
]

// 聊天功能
io.on('connection', (socket) => {
  console.log('新用户连接:', socket.id)

  socket.on('join room', (roomId) => {
    socket.join(roomId)
    io.to(roomId).emit('user joined', socket.id)
  })

  socket.on('chat message', ({ roomId, message }) => {
    io.to(roomId).emit('chat message', {
      userId: socket.id,
      message,
      timestamp: Date.now(),
    })
  })

  // 发送礼物
  socket.on('send gift', async ({ roomId, giftId }) => {
    const gift = gifts.find((g) => g.id === giftId)
    if (!gift) {
      return socket.emit('error', '无效的礼物')
    }

    try {
      // 获取用户信息
      const user = await User.findById(socket.userId)
      if (!user) {
        return socket.emit('error', '用户不存在')
      }

      // 检查余额
      if (user.balance < gift.price) {
        return socket.emit('error', '余额不足')
      }

      // 扣除余额
      user.balance -= gift.price
      await user.save()

      // 广播礼物
      io.to(roomId).emit('gift received', {
        from: socket.id,
        giftId,
        giftName: gift.name,
        price: gift.price,
        timestamp: Date.now(),
      })

      // 更新主播收益
      const host = await User.findById(roomId.split('_')[1])
      if (host) {
        host.income += gift.price
        await host.save()
      }
    } catch (error) {
      socket.emit('error', error.message)
    }
  })

  socket.on('disconnect', () => {
    console.log('用户断开:', socket.id)
  })
})

// 余额提醒
const checkBalanceReminder = async () => {
  try {
    const users = await User.find({
      balance: { $lt: 50 }, // 余额低于50元时提醒
    })

    for (const user of users) {
      // 发送微信模板消息
      if (user.wechatOpenid) {
        await wxPay.sendTemplateMessage({
          touser: user.wechatOpenid,
          template_id: process.env.WECHAT_BALANCE_REMINDER_TEMPLATE_ID,
          url: `${process.env.FRONTEND_URL}/recharge`,
          data: {
            first: {
              value: '您的余额不足，请及时充值',
            },
            keyword1: {
              value: `${user.balance.toFixed(2)}元`,
            },
            keyword2: {
              value: '50元',
            },
            remark: {
              value: '点击立即充值',
            },
          },
        })
      }

      // 发送站内消息
      io.to(user._id.toString()).emit('balanceReminder', {
        balance: user.balance,
        threshold: 50,
      })
    }
  } catch (error) {
    console.error('余额提醒发送失败:', error)
  }
}

// 定时检查余额提醒
setInterval(checkBalanceReminder, 60 * 60 * 1000) // 每小时检查一次

// 启动服务器
const PORT = process.env.PORT || 3000
server.listen(PORT, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`)
  checkBalanceReminder() // 启动时立即检查一次
})
